#include "component.h"
#include "supplier.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <direct.h>
#define MKDIR(path) _mkdir(path)
#else
#include <unistd.h>
#define MKDIR(path) mkdir(path, 0755)
#endif

// --- 文件格式 ---
// data/components.dat
// 纯文本文件，每行一个组件。
// 字段之间用 '|' 分隔。换行符 '\n' 分隔记录。
// 格式：id|型号|名称|封装|描述|供应商ID|数量|价格\n
// 重要提示：假设字段不包含 '|' 或 '\n'。

// --- 辅助函数 ---

// 工具函数：递归创建文件的父目录（只对 data/ 目录及其子目录生效）
// 返回0表示成功，非0表示失败
static int create_parent_directories(const char* filepath) {
   if (!filepath) return -1;
   char buf[512];
   strncpy(buf, filepath, sizeof(buf)-1);
   buf[sizeof(buf)-1] = '\0';
   // 只关心正斜杠和反斜杠
   char* last_sep = NULL;
   for (char* p = buf; *p; ++p) {
       if (*p == '/' || *p == '\\') last_sep = p;
   }
   if (!last_sep) return 0; // 没有子目录，不用创建
   *last_sep = '\0';
   // 必须确保只允许 data 目录为根
   if (strcmp(buf, "data") == 0 || strcmp(buf, "data\\") == 0 || strcmp(buf, "data/") == 0) {
       // 创建 data 目录
       MKDIR(buf);
       return 0;
   } else if (strncmp(buf, "data/", 5) == 0 || strncmp(buf, "data\\", 5) == 0) {
       // 递归创建上级
       create_parent_directories(buf);
       MKDIR(buf);
       return 0;
   } else {
       // 不允许在 data 目录外自动创建
       return -1;
   }
}

static ComponentNode* create_component_node(const Component* data) {
    // DEBUG: Print incoming data
    printf("[DEBUG create_component_node] Creating node for potential ID %d (from data pointer):\n", data->id);
    printf("  Incoming Model: '%s' (len: %zu)\n", data->model, strlen(data->model));
    printf("  Incoming Name: '%s' (len: %zu)\n", data->name, strlen(data->name));
    printf("  Incoming Package: '%s' (len: %zu)\n", data->package, strlen(data->package));
    printf("  Incoming Description: '%s' (len: %zu)\n", data->description, strlen(data->description));
    printf("  Incoming Supplier ID: %d\n", data->supplier_id);
    printf("  Incoming Quantity: %d\n", data->quantity);
    printf("  Incoming Price: %f\n", data->price);

    ComponentNode* newNode = (ComponentNode*)malloc(sizeof(ComponentNode));
    if (!newNode) {
        perror("Failed to allocate memory for ComponentNode");
        return NULL;
    }
    
    // 安全的结构体拷贝，确保字符串正确终止
    memset(&newNode->data, 0, sizeof(Component)); // Good practice
    newNode->data.id = data->id; // Copy ID first
    newNode->data.supplier_id = data->supplier_id;
    newNode->data.quantity = data->quantity;
    newNode->data.price = data->price; // Price is now before image_path
    
    // 无条件安全的字符串拷贝，确保终止符
    strncpy(newNode->data.model, data->model, COMPONENT_MODEL_LEN - 1);
    newNode->data.model[COMPONENT_MODEL_LEN - 1] = '\0';
    
    strncpy(newNode->data.name, data->name, COMPONENT_NAME_LEN - 1);
    newNode->data.name[COMPONENT_NAME_LEN - 1] = '\0';
    
    strncpy(newNode->data.package, data->package, COMPONENT_PACKAGE_LEN - 1);
    newNode->data.package[COMPONENT_PACKAGE_LEN - 1] = '\0';
    
    strncpy(newNode->data.description, data->description, COMPONENT_DESCRIPTION_LEN - 1);
    newNode->data.description[COMPONENT_DESCRIPTION_LEN - 1] = '\0';

    // Add image_path copy
    strncpy(newNode->data.image_path, data->image_path, IMAGE_PATH_LEN - 1);
    newNode->data.image_path[IMAGE_PATH_LEN - 1] = '\0';
    
    newNode->next = NULL;

    // DEBUG: Print data in newly created node
    printf("[DEBUG create_component_node] Node created with ID %d:\n", newNode->data.id);
    printf("  Node Model: '%s' (len: %zu)\n", newNode->data.model, strlen(newNode->data.model));
    printf("  Node Name: '%s' (len: %zu)\n", newNode->data.name, strlen(newNode->data.name));
    printf("  Node Package: '%s' (len: %zu)\n", newNode->data.package, strlen(newNode->data.package));
    printf("  Node Description: '%s' (len: %zu)\n", newNode->data.description, strlen(newNode->data.description));
    printf("  Node Supplier ID: %d\n", newNode->data.supplier_id);
    printf("  Node Quantity: %d\n", newNode->data.quantity);
    printf("  Node Price: %f\n", newNode->data.price);
    printf("  Node Image Path: '%s' (len: %zu)\n", newNode->data.image_path, strlen(newNode->data.image_path)); // New debug print
    return newNode;
}

// --- 核心函数 ---

int load_components(const char* filename, ComponentNode** head) {
    printf("Attempting to open file: %s\n", filename);
    FILE* file = fopen(filename, "r"); // 使用传入的filename参数
    if (!file) {
        perror("Failed to open component file for reading");
        *head = NULL;
        return 0;
    }
    *head = NULL;
    ComponentNode* tail = NULL;
    int count = 0;
    char line_buffer[1024]; // Renamed to avoid confusion with line pointer
    while (fgets(line_buffer, sizeof(line_buffer), file)) {
        // 1. 在主循环开始时：打印原始读取内容
        printf("[DEBUG] Raw line read: %s", line_buffer); // 保留原始换行符以便观察
        line_buffer[strcspn(line_buffer, "\n")] = 0; // Remove newline
        char original_line_for_debug[1024]; // For printing original line if parsing fails
        strncpy(original_line_for_debug, line_buffer, sizeof(original_line_for_debug) -1);
        original_line_for_debug[sizeof(original_line_for_debug)-1] = '\0';

        Component comp_data;
        memset(&comp_data, 0, sizeof(Component));

        // DEBUG: Print initial state of comp_data
        // printf("[DEBUG load_components] Processing line: %s\n", original_line_for_debug); // 已被新的日志替代
        // printf("[DEBUG load_components] Initial comp_data.id = %d\n", comp_data.id);
        // printf("[DEBUG load_components] Initial comp_data.model = '%s'\n", comp_data.model);
        // printf("[DEBUG load_components] Initial comp_data.name = '%s'\n", comp_data.name);

        char* token;
        int field_index = 0;
        // strtok modifies the string, so we operate on line_buffer
        token = strtok(line_buffer, "|");
        while (token != NULL && field_index < 9) { // Changed from 8 to 9 fields
            // 2. 在strtok解析过程中：为每个成功解析的token添加日志
            printf("[DEBUG] Field %d: '%s'\n", field_index, token);
            switch (field_index) {
                case 0: comp_data.id = atoi(token); break;
                case 1:
                    strncpy(comp_data.model, token, COMPONENT_MODEL_LEN - 1);
                    comp_data.model[COMPONENT_MODEL_LEN - 1] = '\0';
                    break;
                case 2:
                    strncpy(comp_data.name, token, COMPONENT_NAME_LEN - 1);
                    comp_data.name[COMPONENT_NAME_LEN - 1] = '\0';
                    break;
                case 3:
                    strncpy(comp_data.package, token, COMPONENT_PACKAGE_LEN - 1);
                    comp_data.package[COMPONENT_PACKAGE_LEN - 1] = '\0';
                    break;
                case 4:
                    strncpy(comp_data.description, token, COMPONENT_DESCRIPTION_LEN - 1);
                    comp_data.description[COMPONENT_DESCRIPTION_LEN - 1] = '\0';
                    break;
                case 5: comp_data.supplier_id = atoi(token); break;
                case 6: comp_data.quantity = atoi(token); break;
                case 7: comp_data.price = atof(token); break; // Price is now field 7
                case 8: // New field: image_path
                    strncpy(comp_data.image_path, token, IMAGE_PATH_LEN - 1);
                    comp_data.image_path[IMAGE_PATH_LEN - 1] = '\0';
                    break;
            }
            token = strtok(NULL, "|");
            field_index++;
        }
        // 3. 在字段处理完成后：添加日志显示最终的 field_index 值
        printf("[DEBUG] Final field_index: %d\n", field_index);

        // 检查是否因为行尾的'|'导致第九个字段（image_path）为空
        // original_line_for_debug 保存了 fgets 读取并移除换行符后的原始行内容
        int original_len = strlen(original_line_for_debug);
        if (original_len > 0 && original_line_for_debug[original_len - 1] == '|' && field_index == 8) {
            // 第九个字段是空的 image_path
            comp_data.image_path[0] = '\0'; // image_path 是 char 数组
            field_index++; // 现在 field_index 应该是 9
            // 可选的调试信息
            // printf("[DEBUG load_components] Handled empty trailing image_path for line: %s. field_index is now %d\n", original_line_for_debug, field_index);
        }

        if (field_index >= 9) { // Changed from 8 to 9 fields
            // DEBUG: Print comp_data before creating node
            // printf("[DEBUG load_components] Parsed comp_data for ID %d:\n", comp_data.id); // 已有更详细的日志
            // printf("  Model: '%s' (len: %zu)\n", comp_data.model, strlen(comp_data.model));
            // printf("  Name: '%s' (len: %zu)\n", comp_data.name, strlen(comp_data.name));
            // printf("  Package: '%s' (len: %zu)\n", comp_data.package, strlen(comp_data.package));
            // printf("  Description: '%s' (len: %zu)\n", comp_data.description, strlen(comp_data.description));
            // printf("  Supplier ID: %d\n", comp_data.supplier_id);
            // printf("  Quantity: %d\n", comp_data.quantity);
            // printf("  Price: %f\n", comp_data.price);
            // printf("  Image Path: '%s' (len: %zu)\n", comp_data.image_path, strlen(comp_data.image_path));

            ComponentNode* newNode = create_component_node(&comp_data);
            // 5. 在节点创建时：检查返回值
            printf("[DEBUG] create_component_node returned: %p\n", (void*)newNode);
            if (newNode) { // If node creation was successful
                ComponentNode* existing_node = find_component_by_id(*head, newNode->data.id);
                if (existing_node) {
                    // Handle duplicate ID
                    printf("[WARNING] Duplicate component ID %d found in file. New entry model: '%s'. Existing entry model: '%s'. Skipping new entry.\n",
                           newNode->data.id, newNode->data.model, existing_node->data.model);
                    free(newNode); // Prevent memory leak for the new duplicate node
                } else {
                    // Add newNode to the list (original logic)
                    if (*head == NULL) {
                        *head = newNode;
                        tail = newNode;
                    } else {
                        tail->next = newNode;
                        tail = newNode;
                    }
                    count++;
                    printf("[INFO] Successfully loaded component: ID=%d, Model=%s, Name=%s\n",
                           newNode->data.id, newNode->data.model, newNode->data.name);
                }
            } else {
                // 5. (续) 如果返回值为NULL，添加错误日志
                printf("[ERROR] Failed to create component node for ID: %d\n", comp_data.id);
            }
        } else {
            // 4. 在字段数量检查时：记录被跳过的行
            printf("[WARNING] Line skipped due to insufficient fields: field_index=%d, line: %s\n", field_index, original_line_for_debug);
        }
    }
    fclose(file);
    printf("Loaded %d components from %s\n", count, filename);
    return count;
}

int save_components(const char* filename, ComponentNode* head) {
    // 先自动创建父目录
    if (create_parent_directories(filename) != 0) {
        fprintf(stderr, "Failed to create parent directory for %s\n", filename);
        return 0;
    }
    FILE* file = fopen(filename, "w"); // 使用传入的filename参数
    if (!file) {
        perror("Failed to open component file for writing");
        return 0;
    }
    ComponentNode* current = head;
    int count = 0;
    while (current != NULL) {
        int written = fprintf(file, "%d|%s|%s|%s|%s|%d|%d|%f|%s\n", // Added %s for image_path
                               current->data.id,
                               current->data.model,
                               current->data.name,
                               current->data.package,
                               current->data.description,
                               current->data.supplier_id,
                               current->data.quantity,
                               current->data.price,
                               current->data.image_path); // Write image_path
        if (written < 0) {
            perror("Failed to write component data to file");
            fclose(file);
            return count;
        }
        current = current->next;
        count++;
    }
    fclose(file);
    printf("Saved %d components to %s\n", count, filename);
    return count;
}

void free_all_components(ComponentNode* head) {
    ComponentNode* current = head;
    ComponentNode* next_node;
    int count = 0;
    while (current != NULL) {
        next_node = current->next;
        free(current);
        current = next_node;
        count++;
    }
    printf("Freed %d component nodes.\n", count);
}

// --- 新增：链表操作函数实现 ---

// 修复后的添加新组件函数 - 改为添加到链表尾部以保持顺序
int add_component(ComponentNode** head, const Component* new_component) {
    if (!head || !new_component) return 0;
    
    // 检查ID是否已存在
    ComponentNode* current = *head;
    while (current) {
        if (current->data.id == new_component->id) {
            return 0; // ID已存在
        }
        current = current->next;
    }
    
    // 创建新节点
    ComponentNode* newNode = create_component_node(new_component);
    if (!newNode) return 0;
    
    // 如果链表为空，直接设为头节点
    if (*head == NULL) {
        *head = newNode;
        return 1;
    }
    
    // 找到链表尾部并插入新节点
    current = *head;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = newNode;
    
    return 1;
}

// 删除指定ID的组件，返回1成功，0未找到
int delete_component(ComponentNode** head, int component_id) {
    if (!head || !*head) return 0;
    ComponentNode* current = *head;
    ComponentNode* prev = NULL;
    while (current) {
        if (current->data.id == component_id) {
            if (prev) {
                prev->next = current->next;
            } else {
                *head = current->next;
            }
            free(current);
            return 1;
        }
        prev = current;
        current = current->next;
    }
    return 0; // 未找到
}

// 查找指定ID的组件，找到返回节点指针，否则NULL
ComponentNode* find_component_by_id(ComponentNode* head, int component_id) {
    ComponentNode* current = head;
    while (current) {
        if (current->data.id == component_id) {
            return current;
        }
        current = current->next;
    }
    return NULL;
}

// 更新指定ID的组件，找到则更新并返回1，否则0
int update_component(ComponentNode* head, const Component* updated_component) {
    if (!updated_component) return 0;
    ComponentNode* node = find_component_by_id(head, updated_component->id);
    if (node) {
        // 安全更新，避免内存问题
        node->data.id = updated_component->id;
        node->data.supplier_id = updated_component->supplier_id;
        node->data.quantity = updated_component->quantity;
        node->data.price = updated_component->price;
        
        // 安全的字符串更新
        strncpy(node->data.model, updated_component->model, COMPONENT_MODEL_LEN - 1);
        node->data.model[COMPONENT_MODEL_LEN - 1] = '\0';
        
        strncpy(node->data.name, updated_component->name, COMPONENT_NAME_LEN - 1);
        node->data.name[COMPONENT_NAME_LEN - 1] = '\0';
        
        strncpy(node->data.package, updated_component->package, COMPONENT_PACKAGE_LEN - 1);
        node->data.package[COMPONENT_PACKAGE_LEN - 1] = '\0';
        
        strncpy(node->data.description, updated_component->description, COMPONENT_DESCRIPTION_LEN - 1);
        node->data.description[COMPONENT_DESCRIPTION_LEN - 1] = '\0';
        
        return 1;
    }
    return 0;
}

// --- 数据验证函数实现 ---

// 验证组件ID：纯数字，1-10位
int validate_component_id(int id) {
    return (id > 0 && id <= 9999999999); // 1-10位数字
}

// 验证供应商ID：纯数字，1-6位
int validate_supplier_id(int supplier_id) {
    return (supplier_id > 0 && supplier_id <= 999999); // 1-6位数字
}

// 验证供应商是否存在：检查供应商ID是否在供应商列表中
int validate_supplier_exists(int supplier_id, SupplierNode* supplier_head) {
    if (!supplier_head) {
        return 0; // 没有供应商列表
    }
    
    SupplierNode* found = find_supplier_by_id(supplier_head, supplier_id);
    return (found != NULL);
}

// 验证组件型号：字母数字组合，无空格，2-30字符，拒绝中文、特殊符号(除-_)
int validate_component_model(const char* model) {
    if (!model || strlen(model) < 2 || strlen(model) > 30) {
        return 0;
    }
    
    for (int i = 0; model[i]; i++) {
        char c = model[i];
        // 只允许字母、数字、连字符、下划线
        if (!isalnum(c) && c != '-' && c != '_') {
            return 0;
        }
        // 拒绝空格
        if (isspace(c)) {
            return 0;
        }
    }
    return 1;
}

// 验证组件名称：中英文+数字，1-50字符，拒绝特殊符号(除空格)、纯符号
int validate_component_name(const char* name) {
    if (!name || strlen(name) < 1 || strlen(name) > 50) {
        return 0;
    }
    
    int has_valid_char = 0;
    for (int i = 0; name[i]; i++) {
        char c = name[i];
        // 允许字母、数字、空格和中文字符（UTF-8）
        if (isalnum(c) || c == ' ') {
            has_valid_char = 1;
        } else if ((unsigned char)c >= 0x80) {
            // 可能是UTF-8多字节字符（中文等），允许
            has_valid_char = 1;
        } else {
            // 其他特殊符号不允许
            return 0;
        }
    }
    
    // 确保不是纯符号或空格
    return has_valid_char;
}

// 验证封装：大写字母+数字组合，2-20字符，拒绝小写字母、中文、特殊符号
int validate_component_package(const char* package) {
    if (!package || strlen(package) < 2 || strlen(package) > 20) {
        return 0;
    }
    
    for (int i = 0; package[i]; i++) {
        char c = package[i];
        // 只允许大写字母和数字
        if (!isupper(c) && !isdigit(c)) {
            return 0;
        }
    }
    return 1;
}

// 验证描述：可选，最大200字符，支持中英文，拒绝超长文本、恶意脚本标签
int validate_component_description(const char* description) {
    if (!description) {
        return 1; // 可选字段，NULL也允许
    }
    
    int len = strlen(description);
    if (len > 200) {
        return 0;
    }
    
    // 检查是否包含恶意脚本标签
    if (strstr(description, "<script") || strstr(description, "</script") ||
        strstr(description, "<iframe") || strstr(description, "<object") ||
        strstr(description, "javascript:") || strstr(description, "vbscript:")) {
        return 0;
    }
    
    return 1;
}

// 验证库存：非负整数，0-999999
int validate_component_quantity(int quantity) {
    return (quantity >= 0 && quantity <= 999999);
}

// 验证价格：正数，最多2位小数，0.01-99999.99
int validate_component_price(float price) {
    if (price < 0.01f || price > 99999.99f) {
        return 0;
    }
    
    // 检查小数位数不超过2位
    float rounded = (float)((int)(price * 100 + 0.5)) / 100.0f;
    return (price == rounded);
}

// 完整验证组件数据（基础版本，不检查供应商存在性）
int validate_component_data(const Component* component, char* error_msg, int error_msg_size) {
    if (!component || !error_msg) {
        return 0;
    }
    
    memset(error_msg, 0, error_msg_size);
    
    if (!validate_component_id(component->id)) {
        snprintf(error_msg, error_msg_size, "组件ID必须是1-10位的正整数");
        return 0;
    }
    
    if (!validate_supplier_id(component->supplier_id)) {
        snprintf(error_msg, error_msg_size, "供应商ID必须是1-6位的正整数");
        return 0;
    }
    
    if (!validate_component_model(component->model)) {
        snprintf(error_msg, error_msg_size, "型号必须是2-30个字符的字母数字组合（可含-_），不能有空格");
        return 0;
    }
    
    if (!validate_component_name(component->name)) {
        snprintf(error_msg, error_msg_size, "名称必须是1-50个字符，支持英文和数字，不能有特殊符号（空格除外）");
        return 0;
    }
    
    if (!validate_component_package(component->package)) {
        snprintf(error_msg, error_msg_size, "封装必须是2-20个字符的大写字母和数字组合");
        return 0;
    }
    
    if (!validate_component_description(component->description)) {
        snprintf(error_msg, error_msg_size, "描述不能超过200个字符，且不能包含恶意脚本标签");
        return 0;
    }
    
    if (!validate_component_quantity(component->quantity)) {
        snprintf(error_msg, error_msg_size, "库存必须是0-999999的非负整数");
        return 0;
    }
    
    if (!validate_component_price(component->price)) {
        snprintf(error_msg, error_msg_size, "价格必须是0.01-99999.99的正数，最多2位小数");
        return 0;
    }
    
    return 1;
}

// 完整验证组件数据（包含供应商存在性检查）
int validate_component_data_with_suppliers(const Component* component, SupplierNode* supplier_head, char* error_msg, int error_msg_size) {
    if (!component || !error_msg) {
        return 0;
    }
    
    // 首先进行基础验证
    if (!validate_component_data(component, error_msg, error_msg_size)) {
        return 0;
    }
    
    // 检查供应商是否存在
    if (!validate_supplier_exists(component->supplier_id, supplier_head)) {
        snprintf(error_msg, error_msg_size, "供应商ID %d 不存在，请先添加该供应商或选择现有供应商", component->supplier_id);
        return 0;
    }
    
    return 1;
}

// 清理价格字符串（移除货币符号）
void clean_price_string(char* price_str) {
    if (!price_str) return;
    
    char* src = price_str;
    char* dst = price_str;
    
    while (*src) {
        if (isdigit(*src) || *src == '.') {
            *dst++ = *src;
        }
        src++;
    }
    *dst = '\0';
}

// 填充默认描述
void fill_default_description(char* description, int max_len) {
    if (!description) return;
    
    if (strlen(description) == 0) {
        strncpy(description, "待完善", max_len - 1);
        description[max_len - 1] = '\0';
    }
}